<template>
  <a-card :bordered='false'>
    <search ref='search' :config='searchConfig' @search='search' @getHeight='getHeight' />
    <div class='page_table'>
      <vxe-grid
        ref='xGrid'
        :border='true'
        :resizable='true'
        :showOverflow='true'
        size='mini'
        :loading='loading'
        :height='pageHeight-seachHeight-90'
        :align='left'
        :columns='columns'
        :data='dataSource'
        :toolbar-config='tableToolbar'
       :checkbox-config="checkboxConfig"
        v-bind='vexConfig'
        @checkbox-change='selectChangeEvent'
        @checkbox-all='selectChangeEvent'
      >
        <template #toolbar_buttons>
          <div class='table-operator'>
            <a-button v-has="'companymgt:add'" @click='handleAdd'>新增</a-button>
            <a-button v-has="'companymgt:delete'" @click='batchDel'>删除</a-button>
            <a-button v-has="'companymgt:synchronization'"  @click=''>同步</a-button>
            <a-button v-has="'companymgt:export'"  @click=''>导出</a-button>
          </div>
        </template>

        <template #detail='{ row,rowIndex }'>
          <a @click='handleDetail(row)'>{{ row.provinceName }}</a>
        </template>
        <template #status='{ row }'>
          <a-switch :checked='row.status' size='small' @change='handleStatus(row,$event)' />
        </template>

        <template #action='{ row}'>
          <a v-has="'companymgt:update'" @click='handleEdit(row)'>编辑</a>
          <a-divider type='vertical' />
          <a v-has="'business:log'" href='javascript:;' @click='handleBusiness("组织管理",row)'>日志</a>
        </template>

        <template #pager>
          <vxe-pager
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :currentPage.sync='ipagination.current'
            :page-size.sync='ipagination.pageSize'
            :total='ipagination.total'
            :pageSizes='ipagination.pageSizeOptions'
            @page-change='handlePageChange'>
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>

    <business-log ref='businessLog'></business-log>
    <form-add-edit ref='formAdd' @ok='modalFormOk'></form-add-edit>
  </a-card>
</template>

<script>
import FormAddEdit from '@comp/view/base-crud/form/FormAddEdit'
import { PageListMixin } from '@/mixins/PageListMixin'
import Vue from 'vue'
import { filterObj } from '@/utils/util'
import { getAction } from '@/api/manage'

export default {
  name: 'product-list',
  mixins: [PageListMixin],
  components: {
    FormAddEdit
  },
  data() {
    return {
      description: '公司管理',
      selectedRowKeys: [],
      importExcelUrl: window._CONFIG['domianURL'] + '/cnProductController/importExcel',
      searchConfig: [
        {
          // label:'订单编号',
          type: 'input',
          name: 'companyCode',
          placeholder: '公司编号'
        },
        {
          // label:'订单编号',
          type: 'input',
          name: 'companyName',
          placeholder: '公司名称'
        }
      ],
      //表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        { type: 'checkbox', width: 60, fixed: 'left' },

        {
          title: '公司编号',
          width: 200,
          minWidth: 200,
          field: 'companyCode'

        },
        {
          title: '公司名称',
          width: 200,
          minWidth: 200,
          ellipsis: true,
          field: 'companyName'
        },
        {
          title: '创建人',
          align: 'left',
          minWidth:80,
          field: 'createName',
        },
        {
          title: '创建时间',
          align: 'left',
          minWidth:80,
          field: 'createTime',
        },
        {
          title: '更新人',
          align: 'left',
          minWidth:80,
          field: 'updateName',
        },
        {
          title: '更新时间',
          align: 'left',
          minWidth:80,
          field: 'updateTime',
        },
        {
          title: '操作',
          field: 'action',
          align: 'center',
          fixed: 'right',
          width: 120,
          minWidth: 200,
          slots: {
            default: 'action'
          }
        }
      ],
      url: {
        list: '/company/cnCompany/findPageList',
        delete: '/company/cnCompany/delete',
        // detail: '/company/cnCompany/saveOrUpdate',
        deleteBatch: '/company/cnCompany/deleteBatch',
        exportXlsUrl: window._CONFIG['domianURL'] + '/cnProductController/exportXls',
        deleteTag: '/cnTerminalController/deleteLabels',
        saveOrUpdateTag: window._CONFIG['domianURL'] + '/cnTerminalController/saveOrUpdateLabels',
        startOrStopUrl: window._CONFIG['domianURL'] + '/cnProductController/startOrStop',
        // 导入接口
        importExcelUrl: window._CONFIG['domianURL'] + '/cnProductController/importExcel'
      }
    }
  },
  created() {
    this.initColumns()
  },
  methods: {

    startorstop: function(status) {
      if (!this.url.startOrStopUrl) {
        this.$message.error('请设置url启用停用!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认修改',
          content: '是否修改选中数据?',
          onOk: function() {
            that.loading = true
            getAction(that.url.startOrStopUrl, { ids: ids, status: status }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })
      }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    getQueryParams() {
      //高级查询器
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)

      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      delete param.birthdayRange //范围参数不传递后台
      return filterObj(param)
    },


    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.field == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.field)) {
          return true
        }
        return false
      })
      this.columns = cols
    },

    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function(item, i, array) {
          allSettingColumns.push(item.field)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.field == 'action') {
            return true
          }
          if (colSettings.includes(item.field)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },

    async handleAdd(record = {}, title = '新增', disabled = false, disableSubmit = false) {
      if (record.id && this.url.detail) {
        const res = await getAction(this.url.detail, { id: record.id })
        if (res.success) {
          if (res.result) {
            record = res.result
          }
        }
      }
      let config = {
        title: title,
        width: 500,
        addOrUpdateUrl: `${window._CONFIG['domianURL']}/company/cnCompany/saveOrUpdate`,  //审核地址
        method: 'post',
        list: [
          {
            label: '公司编号',
            type: 'input',
            placeholder: '公司编号',
            disabled: disabled,
            name: 'companyCode',  // 后台接受字段
            check: { rules: [{ required: true, message: '公司编号' }] }
          },
          {
            label: '公司名称',
            type: 'input',
            placeholder: '公司名称',
            disabled: disabled,
            name: 'companyName'  // 后台接受字段
          }
        ]
      }
      this.$refs.formAdd.edit(record, config)
      this.$refs.formAdd.disableSubmit = disableSubmit
    },
    handleEdit: async function(row) {
      let config = {
        title: '编辑',
        width: 500,
        addOrUpdateUrl: `/company/cnCompany/saveOrUpdate`,  //审核地址
        method: 'post',
        list: [
          {
            label: '公司编号',
            type: 'input',
            name: 'companyCode',  // 后台接受字段
            placeholder: '',
            check: { rules: [{ required: true, message: '请填写公司编码', whitespace: true }] }
          },
          {
            label: '公司名称',
            type: 'input',
            name: 'companyName',  // 后台接受字段
            placeholder: ''
          }
        ]
      }
      this.$refs.formAdd.edit(row, config)
      this.$refs.formAdd.disableSubmit = false
    },
  }

}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>